package com.wln.sms.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.wln.common.utils.R;
import com.wln.sms.sms.entity.GoodsActivityEntity;
import com.wln.sms.sms.feign.GoodsFeignService;
import com.wln.sms.sms.service.GoodsActivityService;
import com.wln.sms.sms.util.IdWorker;
import com.wln.sms.sms.vo.ActivityGoodsVo;
import com.wln.sms.sms.vo.AddOrderVo;
import com.wln.sms.sms.vo.GoodsVo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wln.common.utils.PageUtils;
import com.wln.common.utils.Query;

import com.wln.sms.sms.dao.OrderInfoDao;
import com.wln.sms.sms.entity.OrderInfoEntity;
import com.wln.sms.sms.service.OrderInfoService;
import org.springframework.transaction.annotation.Transactional;


@Service("orderInfoService")
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoDao, OrderInfoEntity> implements OrderInfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedissonClient client;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private GoodsFeignService goodsFeignService;
    @Autowired
    private GoodsActivityService goodsActivityService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<OrderInfoEntity> wrapper = new QueryWrapper<>();
        String userid = (String) params.get("userid");
        wrapper.eq("user_id", userid);
        IPage<OrderInfoEntity> page = this.page(
                new Query<OrderInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage1(Map<String, Object> params) {
        QueryWrapper<OrderInfoEntity> wrapper = new QueryWrapper<>();

        IPage<OrderInfoEntity> page = this.page(
                new Query<OrderInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<OrderInfoEntity> findno() {
        List<OrderInfoEntity> status = baseMapper.selectList(new QueryWrapper<OrderInfoEntity>().eq("status", 0));
        return status;
    }

    //如果用户五分钟之内没有支付
    @Scheduled(cron = "* 0/5 * * * *")
    public void upall() {

        List<OrderInfoEntity> status = baseMapper.selectList(new QueryWrapper<OrderInfoEntity>().eq("status", 0));

        BoundHashOperations orderinfo = redisTemplate.boundHashOps("orderinfo");

        BoundHashOperations goods = redisTemplate.boundHashOps("goods");

        BoundHashOperations activitylist = redisTemplate.boundHashOps("activitylist");

        for (OrderInfoEntity orderInfoEntity : status) {

            OrderInfoEntity o = (OrderInfoEntity) orderinfo.get(orderInfoEntity.getOorderId());

            Date createDate = o.getCreateDate();

            long time = createDate.getTime();

            long time2 = time + 60 * 1000 * 5;

            if (time2 < new Date().getTime()) {

                System.out.println("到期未支付取消订单");

                o.setStatus(5);

                orderinfo.put(o.getOorderId(), o);

                Integer o1 = (Integer) goods.get(o.getGoodsId());

                goods.put(o.getGoodsId(), (o1+o.getGoodsCount()));

                GoodsActivityEntity o2 = (GoodsActivityEntity) activitylist.get(o.getActivityId());

                o2.setStockCount(o2.getStockCount() + o.getGoodsCount());

                activitylist.put(o.getActivityId(), o2);
            }
        }
    }

    //更新数据库库存
    @Scheduled(cron = "0/5 * * * * *")
    public void uploaddredis() {

        //更新商品表
        R list = goodsFeignService.list();

        List<GoodsVo> data = list.getData(new TypeReference<List<GoodsVo>>() {
        });
        BoundHashOperations goods = redisTemplate.boundHashOps("goods");

        for (GoodsVo goodsVo : data) {

            Integer o = (Integer) goods.get(goodsVo.getGoodsId());

            goodsVo.setGoodsStock(o);

            goodsFeignService.update(goodsVo);


        }

        //更新活动表
        List<GoodsActivityEntity> list1 = goodsActivityService.list();

        BoundHashOperations activitylist = redisTemplate.boundHashOps("activitylist");

        List<GoodsActivityEntity> values1 = activitylist.values();

        for (GoodsActivityEntity activityEntity : values1) {

            for (GoodsActivityEntity entity : list1) {

                if (activityEntity.getActivityId().equals(entity.getActivityId())) {

                    entity.setStockCount(activityEntity.getStockCount());

                    goodsActivityService.updateById(entity);
                }
            }
        }

        BoundHashOperations orderinfo = redisTemplate.boundHashOps("orderinfo");
        List<OrderInfoEntity> values = orderinfo.values();
        List<OrderInfoEntity> orderInfoEntities = baseMapper.selectList(null);
        if (orderInfoEntities == null) {
            for (OrderInfoEntity value : values) {
                baseMapper.insert(value);
            }
        } else {
            for (OrderInfoEntity value : values) {
                boolean flag = false;
                for (OrderInfoEntity infoEntity : orderInfoEntities) {
                    if (value.getOorderId().equals(infoEntity.getOorderId())) {
                        flag = true;
                        baseMapper.updateById(value);
                    }
                }
                if (flag == false) {
                    baseMapper.insert(value);
                }

            }
        }


    }

    @Override
    @Transactional
    public R add(ActivityGoodsVo activityGoodsVo) {

        RLock lock1 = client.getLock("lock1");


        try {

            lock1.lock();
            boolean flag = false;
            BoundHashOperations goods = redisTemplate.boundHashOps("goods");

            Integer o = (Integer) goods.get(activityGoodsVo.getGoodsId());

            if (o > 0) {

                BoundHashOperations orderinfo = redisTemplate.boundHashOps("orderinfo");

                List<OrderInfoEntity> values = orderinfo.values();

                for (OrderInfoEntity entity : values) {

                    if (entity.getUserId().equals(activityGoodsVo.getUserId()) && entity.getActivityId().equals(activityGoodsVo.getActivityId())&&entity.getStatus()==5) {
                        flag = true;
                        break;
                    }
                }

                if (flag == false) {
                    OrderInfoEntity infoEntity = new OrderInfoEntity();

                    infoEntity.setOorderId(idWorker.nextId());

                    infoEntity.setGoodsAddrId(12l);

                    infoEntity.setActivityId(activityGoodsVo.getActivityId());

                    infoEntity.setStatus(0);

                    infoEntity.setGoodsId(activityGoodsVo.getGoodsId());

                    infoEntity.setUserId(activityGoodsVo.getUserId());

                    infoEntity.setGoodsCount(activityGoodsVo.getGoodsCount());

                    infoEntity.setGoodsPrice(activityGoodsVo.getActivityPrices());

                    infoEntity.setGoodsName(activityGoodsVo.getGoodsName());

                    infoEntity.setGoodsChannel(1);

                    infoEntity.setCreateDate(new Date());

                    infoEntity.setGoodsImg(activityGoodsVo.getGoodsImg());

                    orderinfo.put(infoEntity.getOorderId(),infoEntity);

                    rabbitTemplate.convertAndSend("order", JSON.toJSONString(activityGoodsVo));

                    return R.ok();
                }
                return R.error("您已经添加过该活动的订单");
            }
            return R.error("库存不足");


        }finally {
            lock1.unlock();
        }

    }


//    @Override
//    public R add(OrderInfoEntity orderInfoEntity) {
//        RLock lock = client.getLock("lock");
//        try {
//            lock.lock();
//            OrderInfoEntity orderInfoEntity = new OrderInfoEntity();
//            Long l = idWorker.nextId();
//            orderInfoEntity.setOorderId(l);
//            orderInfoEntity.setCreateDate(new Date());
//            orderInfoEntity.setActivityId(activityEntity.getActivityId());
//            orderInfoEntity.setUserId(activityEntity.getUserId());
//            orderInfoEntity.setGoodsAddrId(0l);
//            orderInfoEntity.setGoodsCount(activityEntity.getStockCount());
//            orderInfoEntity.setGoodsPrice(activityEntity.getActivityPrice());
//            orderInfoEntity.setGoodsChannel(0);
//
//            R byGoodsId = goodsFeignService.getByGoodsId(activityEntity.getGoodsId());
//            GoodsVo data = byGoodsId.getData(new TypeReference<GoodsVo>() {
//            });
//            orderInfoEntity.setGoodsName(data.getGoodsName());
//            orderInfoEntity.setStatus(0);
//            orderInfoEntity.setPayDate(null);
//            orderInfoEntity.setGoodsId(data.getGoodsId());
//
//            QueryWrapper<OrderInfoEntity> w = new QueryWrapper<>();
//            w.eq("user_id",activityEntity.getUserId()).eq("activity_id",activityEntity.getActivityId());
//            List<OrderInfoEntity> list = orderInfoService.list(w);
//
//
//            if (list.size()==0) {
//                System.out.println("占坑成功");
//                if (data.getGoodsStock() >= activityEntity.getStockCount()) {
//                    AddOrderVo addOrderVo = new AddOrderVo();
//                    addOrderVo.setGoodsVo(data);
//                    addOrderVo.setOrderInfoEntity(orderInfoEntity);
//                    GoodsActivityEntity goodsActivityEntity = goodsActivityDao.selectById(activityEntity.getActivityId());
//                    addOrderVo.setGoodsActivityEntity(goodsActivityEntity);
//                    addOrderVo.setStockCount(activityEntity.getStockCount());
//                    rabbitTemplate.convertAndSend("order", JSON.toJSONString(addOrderVo));
//                    return R.ok();
//                }
//            }else {
//                return R.error("您已经添加过该活动的订单");
//            }
//        }finally {
//            lock.unlock();
//        }
//        return R.error("库存不足");
//    }
//执行支付减库存
//    @Override
//    public void add(GoodsActivityEntity activityEntity) {
//        baseMapper.insert(activityEntity);
//    }

//远程调用小凯的接口
//    @Override
//    public void add(GoodsActivityEntity activityEntity) {
//        MiaoActivityEntity entity = new MiaoActivityEntity();
//        entity.setMiaoId(activityEntity.getActivityId().intValue());
//        entity.setCount(activityEntity.getStockCount());
//        entity.setStartDate(new Date());
//        entity.setGoodsId(activityEntity.getGoodsId().intValue());
//        entity.setGoodsPrice(activityEntity.getActivityPrice());
//        entity.setUserId(activityEntity.getUserId());
//        orderFeignService.save(entity);
//    }



}